<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>可拖动的 DIV</title>
    <style>
        #draggable {
            width: 100px;
            height: 100px;
            background-color: lightcoral;
            position: absolute; /* 使 div 可以自由移动 */
            cursor: move; /* 提示用户可以拖动 */
        }
    </style>
</head>
<body>
    <div id="draggable">
    </div>
    <script>
        const draggable = document.getElementById('draggable');

        draggable.addEventListener('mousedown', function(event) {
            let offsetX = event.clientX - draggable.getBoundingClientRect().left;
            let offsetY = event.clientY - draggable.getBoundingClientRect().top;

            function mouseMoveHandler(event) {
                draggable.style.left = `${event.clientX - offsetX}px`;
                draggable.style.top = `${event.clientY - offsetY}px`;
            }

            function mouseUpHandler() {
                document.removeEventListener('mousemove', mouseMoveHandler);
                document.removeEventListener('mouseup', mouseUpHandler);
            }

            document.addEventListener('mousemove', mouseMoveHandler);
            document.addEventListener('mouseup', mouseUpHandler);
        });
    </script>
</body>
</html>